package com.atguigu.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: kaiyi
 * @create: 2020-09-04 11:19
 */
public class ThreadTest {

  public static void main(String[] args) {
    CompletableFuture.runAsync(()->{
      System.out.println("runAsync 不支持返回值");
    }).whenComplete((t,u)->{
      System.out.println("runAsync 完成"  + t);

    });

    /** 第二种 supplyAsync 支持返回值 */
    CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
      int i = 10;
      return i;
    }).whenComplete((t, u) -> {
      System.out.println("supplyAsync 完成,返回值是" + t);
    });

  }

  public static void threadMain(String[] args) {
   System.out.println("main...start...");
    /**
     * 1)、继承Thread
     *    Thread01 thread = new Thread01();
     *     thread.start(); // 启动线程
     *
     * 2)、实现Runnable接口
     *     Runable01 runable01 = new Runable01()
     *     new Thread(runable01).start();
     *
     * 3)、实现Callable接口+FutureTask(可以拿到返回结果，可以处理异常）
     *     FutureTask<Integer> FutureTask = new FutureTask<>(new Callable01());
     *     new Thread(futureTask).start();
     *     // 阻塞等待整个线程执行完成，获取返回结果
     *     Integer integer = futureTask.get();
     *
     * 4)、线程池[ExecutorService]
     *   给线程池直接提交任务。
     *   service.execute(new Runable01());
     *   创建：
     *      ①、Excutors
     *      ②、new ThreadPoolExecutor
     *
     *    Future:可以获取到异步结果
     */
    Thread01 thread01 = new Thread01();
    thread01.start(); // 启动线程

    System.out.println("main...end...");


  }

  public static class Thread01 extends  Thread{

    @Override
    public void run(){
      System.out.println("当前线程：" + Thread.currentThread().getId());

      int i = 10 / 2;
      System.out.println("运行结果：" + i);
    }
  }

  private static void threadPool(){
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
        5,
        200,
        10L,
        TimeUnit.SECONDS,
        new LinkedBlockingDeque<Runnable>(10000),
        Executors.defaultThreadFactory(),
        new ThreadPoolExecutor.AbortPolicy()
    );

    // 定时任务的线程池
    ExecutorService service = Executors.newScheduledThreadPool(2);

  }

}
